import Vue from 'vue'
import Router from 'vue-router'
import Cookies from "js-cookie";
Vue.use(Router)

export const constantRoutes = [
    {
        path:'/login',
        component: () => import('@/views/login/Login'),
        hidden :true
    },
    {
        path:'/register',
        component:() => import('@/views/normal/UserRegister'),
    },
    {
        path:'/normal',
        redirect: '/normal/home',
        component:() => import('@/App'),
        children: [
            {
                path:'add',
                component:() => import('@/views/normal/AddMoveInfo')
            },
            {
                path:'home',
                component:() => import('@/views/normal/JumpPage')
            },
            {
                path:'moveInfo',
                component:() => import('@/views/normal/UserMoveHomeInfo')
            }
        ]
    },
    {
        path:'/',
        component:() => import('@/layout/index'),
        children:[
            {
                path: 'mh/list',
                component:() => import('@/views/movehome/MoveHomeList'),
            },
            {
              path: 'mh/add',
                component:() => import('@/views/movehome/MoveHomeAdd')
            },
            {
                path:'user/list',
                component:() => import('@/views/user/UserList'),
            },
            {
                path:'movehome',
                component: () => import('@/views/home/Home')
            },
            {
                path:'user/add',
                component:()=> import('@/views/user/UserAdd')
            },
            {
                path: '/person',
                component:() => import('@/views/person/PersonCenter')
            }
        ]
    }
]

const createRouter = () => new Router({
    scrollBehavior: () => ({ y: 0 }),
    mode: 'history',
    routes: constantRoutes
})

const router = createRouter()

export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher
}

router.beforeEach((to, from, next) => {
    const cookie = Cookies.get('user')
    if (cookie) {
        const user = JSON.parse(cookie)
        if (user.role === 1) {
            if (to.path.indexOf('/normal') === -1) {
                router.push({path:'/normal/home'})
            }
        } else {
            if (to.path === '/') {
                router.push({path:'/movehome'})
            }
        }
    }


    if (to.path === '/login') {
        if (cookie) {
            const user = JSON.parse(cookie)
            if (user.role === 1) {
                router.push({path:'/normal/home'})
            } else {
                // 有则跳回主页
                router.push({path:'/'})
            }
        } else {
            // 没有则放行
            next()
        }
    }
    next()
})


export default router
